package com.gp.gback.system.common.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

/**
 * Created by kent-huang on 16/8/22.
 */
public class HexUtil {

    private static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    private static String hexString = "0123456789abcdef";


    public static Key getKey(String keyContent) {
        Key key = null;
        try {
            key = new SecretKeySpec(keyContent.getBytes(), "AES");
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
        return key;
    }

    public static byte[] encrypt(byte[] bytes, Key key) {
        byte[] target = null;
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            target = cipher.doFinal(bytes);
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
        return target;
    }

    public static String bytesToHex(byte bytes[], int m, int n) {
        StringBuffer sb = new StringBuffer(2 * n);
        int k = m + n;
        for (int i = m; i < k; i++) {
            appendHexPair(bytes[i], sb);
        }
        return sb.toString();
    }

    public static String bytesToHex(byte bytes[]) {
        return bytesToHex(bytes, 0, bytes.length);
    }

    private static void appendHexPair(byte bt, StringBuffer sb) {
        char c0 = hexDigits[(bt & 0xf0) >> 4];
        char c1 = hexDigits[bt & 0xf];
        sb.append(c0);
        sb.append(c1);
    }

    public static byte[] hexToBytes(String hex) {
        int len = (hex.length() / 2);
        byte[] bytes = new byte[len];
        char[] charArray = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            bytes[i] = (byte) (toByte(charArray[pos]) << 4 | toByte(charArray[pos + 1]));
        }
        return bytes;
    }

    private static byte toByte(char c) {
        return (byte) hexString.indexOf(c);
    }

    public static byte[] decrypt(byte[] bytes, Key key) {
        byte[] decryptedData = null;
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            decryptedData = cipher.doFinal(bytes);
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
        return decryptedData;
    }
}
